package com.haozi.core;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.haozi.config.GlobalConfig;
import com.haozi.dto.PointResult;
import com.haozi.event.GetPointAfterEvent;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * @author zyh
 * @version 1.0
 * @date 2022/4/27 11:41 上午
 */
@Component
@Slf4j
public class DingDingDataHandler implements ApplicationListener<GetPointAfterEvent> {

    /**
     * 上次点数
     */
    BigDecimal lastPoint;

    @Override
    public void onApplicationEvent(GetPointAfterEvent event) {

        PointResult pointResult = event.getPointResult();
        if (lastPoint == null) {
            lastPoint = pointResult.getCurrentPoint();
        }
        BigDecimal subtract = pointResult.getCurrentPoint().subtract(lastPoint);
        log.info("当前点数{},较之前浮动点数{}",pointResult.getCurrentPoint().toPlainString(),subtract.toPlainString());
        //起伏小于阈值不做处理
        if(GlobalConfig.THRESHOLD_POINT.compareTo(subtract.abs())>0){
            return;
        }
        sendMesg(StrUtil.format("浮动点数{},当前点数{},",subtract.toPlainString(),pointResult.getCurrentPoint().toPlainString()));
        lastPoint = pointResult.getCurrentPoint();
    }

    private void sendMesg(String message){


        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=37b2a9a7be6dc06e9b6236702c967bea0dd342d30e5d1ff5a6c8319187311fdb");
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent("测试文本消息");
        request.setText(text);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();


        at.setIsAtAll(true);

        request.setAt(at);

        request.setMsgtype("link");
//        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
//        link.setMessageUrl("https://www.dingtalk.com/");
//        link.setPicUrl("");
//        link.setTitle("涨幅超过阈值提醒");
//        link.setText("这个即将发布的新版本，创始人xx称它为红树林。而在此之前，每当面临重大升级，产品经理们都会取一个应景的代号，这一次，为什么是红树林");
//        request.setLink(link);

        request.setMsgtype("markdown");
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle("涨幅超过阈值提醒");
        markdown.setText(message);
        request.setMarkdown(markdown);
        try {
            OapiRobotSendResponse response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }


    }
}
